<template>
  <div class="intervention-management">
    <h3>当前待处理预警 ({{ pendingAlerts.length }})</h3>

    <!-- 预警列表 -->
    <div class="alert-list">
      <div v-for="alert in pendingAlerts" :key="alert.id" class="alert-item">
        <div class="alert-header">
          <span class="student-name">{{ alert.studentName }}</span>
          <el-tag :type="alertTypeMap[alert.type].color">
            {{ alertTypeMap[alert.type].label }}
          </el-tag>
        </div>
        <div class="alert-details">
          {{ alert.details }}
          <span class="timestamp">{{ formatTime(alert.timestamp) }}</span>
        </div>
        <div class="action-buttons">
          <el-button
              type="primary"
              size="small"
              @click="showInterventionDialog(alert)"
          >
            制定干预措施
          </el-button>
        </div>
      </div>
    </div>

    <!-- 干预措施对话框 -->
    <intervention-dialog
        v-model="showDialog"
        :student-id="selectedStudentId"
        @submit="handleInterventionSubmit"
    />
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useAlertStore } from '@/stores/alertStore'
import { storeToRefs } from 'pinia'
import { format } from 'date-fns'
import InterventionDialog from '@/components/InterventionDialog.vue'

const alertStore = useAlertStore()
const { pendingAlerts } = storeToRefs(alertStore)

const alertTypeMap = {
  score: { label: '成绩预警', color: 'danger' },
  attendance: { label: '出勤预警', color: 'warning' },
  assignment: { label: '作业预警', color: 'info' }
}

const showDialog = ref(false)
const selectedStudentId = ref(null)

const formatTime = (date) => {
  return format(new Date(date), 'yyyy-MM-dd HH:mm')
}

const showInterventionDialog = (alert) => {
  selectedStudentId.value = alert.studentId
  showDialog.value = true
}

const handleInterventionSubmit = async (formData) => {
  await alertStore.handleAlert(formData.alertId)
  // 提交干预措施到后端
  await axios.post('/interventions', {
    ...formData,
    teacherId: alertStore.currentTeacher.id
  })
  showDialog.value = false
}
</script>

<style scoped>
.alert-item {
  margin-bottom: 16px;
  padding: 12px;
  border: 1px solid #eee;
  border-radius: 4px;
}

.alert-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.student-name {
  font-weight: bold;
}

.timestamp {
  color: #666;
  font-size: 0.8em;
  margin-left: 12px;
}
</style>